package cn.wenzy.aurora.framework.support.validation.interpolation;

import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator;
import org.springframework.validation.beanvalidation.MessageSourceResourceBundleLocator;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Locale;

public class MessageInterpolator extends ResourceBundleMessageInterpolator {

    public MessageInterpolator(MessageSourceResourceBundleLocator messageSourceResourceBundleLocator) {
        super(messageSourceResourceBundleLocator);
    }

    @Override
    public String interpolate(String message, Context context) {
        Locale locale = getLocale();
        return super.interpolate(message, context, locale);
    }

    private Locale getLocale() {
        Locale locale = Locale.getDefault();
        //获取request的请求语言，因为在编程式的校验时，是通过Locale.getDefault()获取语言的，导致spring的LocaleResolver配置无效
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null != attributes && null != attributes.getRequest()) {
            locale = attributes.getRequest().getLocale();
        }
        return locale;
    }
}
